app.controller('loanDetailReadCtl',
     function($scope, $http, rest, $compile, $location, ngDialog, tipService, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad, $timeout, uploadConf, uploadprefix) {

          var token = $window.localStorage.getItem("token");

          $scope.uploadprefix = uploadprefix;

          if ($window.localStorage.getItem("loanId")) {
               $scope.decorteOrderInfoId = $window.localStorage.getItem("loanId");
          }
          $scope.queryParams1 = {
               decorteOrderInfoId: $scope.decorteOrderInfoId
          }

          applyHouseDetail();

          function applyHouseDetail() {
               rest.decoJava({
                    type: "post",
                    url: "/tenancy-sys/admin/decorateOrderInfo/queryDecorateOrderInfoById",
                    data: {
                         decorteOrderInfoId: $scope.decorteOrderInfoId,
                    },
                    beforeSend: function(request) {
                         request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                         if (data.code == "0000") {
                              $scope.$apply(function() {
                                   $scope.queryParams1 = data.result;
                                   $scope.landlord = data.result.landlord;
                                   if ($scope.landlord.landlordType == "OWNER") {
                                        $scope.landlordType = "业主（产权拥有）";
                                   } else if ($scope.landlord.landlordType == "PERSON") {
                                        $scope.landlordType = "职业房东（个人性质）";
                                   } else if ($scope.landlord.landlordType == "ENTERPRISE") {
                                        $scope.landlordType = "职业房东（企业性质）";
                                   }
                              })

                              //判断是否是指派过的房源
                              if ($scope.queryParams1.auditorId == null) {
                                   $scope.assigned = 0;
                                   $('#totalDecorationMoney').attr('readonly', 'readonly');
                                   $('#suggest').attr('readonly', 'readonly');
                              } else {
                                   $scope.assigned = 1;
                                   $('#totalDecorationMoney').removeAttr('readonly');
                                   $('#suggest').removeAttr("readonly");
                              }

                              if ($scope.queryParams1.orderProcessStatus == "OrderEffective") {
                                   $scope.loanFinished = 1;
                                   $scope.loanBox = 1;
                                   $('#totalDecorationMoney').attr('readonly', 'readonly');
                                   $('#suggest').removeAttr('readonly');
                              } else if ($scope.queryParams1.orderProcessStatus == "OrderCancelled" || $scope.queryParams1.orderProcessStatus == "OrderRepayment") {
                                   $scope.loanFinished = 1;
                                   $scope.loanBox = 0;
                                   $('#totalDecorationMoney').attr('readonly', 'readonly');
                                   $('#suggest').attr('readonly', 'readonly');
                              }

                              if ($scope.queryParams1.orderProcessStatus == "OrderWaitReview") {
                                   $scope.statusStr = "订单待审核";
                              } else if ($scope.queryParams1.orderProcessStatus == "OrderEffective") {
                                   $scope.statusStr = "订单已通过";
                              } else if ($scope.queryParams1.orderProcessStatus == "OrderCancelled") {
                                   $scope.statusStr = "订单未通过";
                              } else if ($scope.queryParams1.orderProcessStatus == "OrderRepayment") {
                                   $scope.statusStr = "订单还款中";
                              } else if ($scope.queryParams1.orderProcessStatus == "OrderIsOver") {
                                   $scope.statusStr = "订单已完结";
                              }

                              $scope.$apply();

                         } else {
                              tipService.show("body", {
                                   message: data.message,
                                   notice: "danger"
                              }, 3);
                         }

                    }
               });
          }

          $("#suggest").on("input propertychange", function() {
               var $this = $(this),
                    _val = $this.val(),
                    count = "";
               if (_val.length > 200) {
                    $this.val(_val.substring(0, 200));
               }
               count = 200 - $this.val().length;
               $("#text-count").text(count);
          });

          //查看流转记录
          $scope.viewLoanRecord = function() {
               ngDialog.openConfirm({
                    template: 'views/loanOrder/viewLoanRecord.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/controllers/loanOrder/viewLoanRecord.js'])
                                   });
                         }
                    },
                    data: {
                         id: $scope.queryParams1.id,
                    },
                    scope: $scope,
                    width: 900,
                    // height: 700
               }).then(function(data) {

               }, function(reason) {

               });
          }

          //认领
          $scope.claimHouse = function() {
               ngDialog.openConfirm({
                    template: 'js/module/fund/claimLoan.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/module/fund/claimLoan.js'])
                                   });
                         }
                    },
                    data: {
                         loanId: $scope.decorteOrderInfoId
                    },
                    scope: $scope,
                    width: 600,
                    // height: 700
               }).then(function(data) {

               }, function(reason) {
                    applyHouseDetail();
               });
          }

          //通过
          $scope.passThrough = function() {
               rest.decoJava({
                    type: "post",
                    url: "/tenancy-sys/admin/decorateOrderInfo/updateOrderProcessStatus",
                    data: {
                         decorateOrderInfoId: $scope.decorteOrderInfoId,
                         orderProcessStatus: "OrderEffective",
                         remark: $scope.queryParams1.remark,
                         orderReplyAmount: $scope.queryParams1.orderReplyAmount
                    },
                    beforeSend: function(request) {
                         request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                         if (data.code == 0000) {
                              tipService.show("body", {
                                   message: data.message,
                              }, 3);
                              // $state.go('app.house.houseManageList');
                              // history.go(-1);
                              window.close();
                         } else {
                              tipService.show("body", {
                                   message: data.message,
                                   notice: "danger"
                              }, 3);
                              return;
                         }
                    }
               });
          }

          //拒绝
          $scope.refuse = function() {
               rest.decoJava({
                    type: "post",
                    url: "/tenancy-sys/admin/decorateOrderInfo/updateOrderProcessStatus",
                    data: {
                         decorateOrderInfoId: $scope.decorteOrderInfoId,
                         orderProcessStatus: "OrderCancelled",
                         remark: $scope.queryParams1.remark,
                         orderReplyAmount: $scope.queryParams1.orderLoanAmount
                    },
                    beforeSend: function(request) {
                         request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                         if (data.code == 0000) {
                              tipService.show("body", {
                                   message: data.message,
                              }, 3);
                              // $state.go('app.house.houseManageList');
                              // history.go(-1);
                              window.close();
                         } else {
                              tipService.show("body", {
                                   message: data.message,
                                   notice: "danger"
                              }, 3);
                              return;
                         }
                    }
               });
          }

          //放款
          $scope.loanBtn = function() {
               rest.decoJava({
                    type: "post",
                    url: "/tenancy-sys/admin/decorateOrderInfo/decorateOrderLoan",
                    data: {
                         decorateOrderInfoId: $scope.decorteOrderInfoId,
                         // remark: $scope.queryParams1.remark,
                         // orderReplyAmount: $scope.queryParams1.orderLoanAmount,
                         loanDate: $scope.queryParams1.loanDate
                    },
                    beforeSend: function(request) {
                         request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                         if (data.code == 0000) {
                              tipService.show("body", {
                                   message: data.message,
                              }, 3);
                              // $state.go('app.house.houseManageList');
                              // history.go(-1);
                              $scope.tableLoanDetailList.fnClearTable();
                              applyHouseDetail();
                              // window.close();
                         } else {
                              tipService.show("body", {
                                   message: data.message,
                                   notice: "danger"
                              }, 3);
                              return;
                         }
                    }
               });
          }

          var tmpHouseIdArr = "";
          initDataTables();
          var tabHeight = ($window.innerHeight - 340) + "px"; //table内容区高度


          function initDataTables() {
               $scope.dataTableLoanDetailList = {
                    "sAjaxSource": "/tenancy-sys/admin/decorateOrderInfo/queryDecorateOrderInfoById",
                    "bAutoWidth": true,
                    "iDisplayLength": 3,
                    "dom": "t",
                    "sScrollY": tabHeight, //给定高度，内容超出即出滚动条
                    "bScrollCollapse": false, //不管内容多少高度固定
                    "aoColumns": [{
                         "mDataProp": "periodNum",
                         "sTitle": "期号",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "planRepaymentDate",
                         "sTitle": "预还款日",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "repaymentDate",
                         "sTitle": "实际还款日",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "planRepaymentAmount",
                         "sTitle": "应还本金",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "street",
                         "sTitle": "应还利息",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "roomNo",
                         "sTitle": "应还金额",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "realRepaymentAmount",
                         "sTitle": "实还金额",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "overdueDays",
                         "sTitle": "逾期天数",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "overdueFee",
                         "sTitle": "逾期罚息",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "subtractOverdueFee",
                         "sTitle": "罚息减免",
                         "sDefaultContent": "",
                         "sClass": "center"
                    }, {
                         "mDataProp": "planStatus", //0未还 1已还
                         "sTitle": "还款状态",
                         "sDefaultContent": "",
                         "sClass": "center repayStatus"
                    }, {
                         "mDataProp": "operate",
                         "sTitle": "交易记录",
                         "sDefaultContent": "",
                         "sClass": "center viewRecord"
                    }, {
                         "mDataProp": "operate",
                         "sTitle": "操作",
                         "sDefaultContent": "",
                         "sClass": "center handle-td"
                    }],
                    "fnRowCallback": function(nRow, aData, iDisplayIndex) {
                         var btnStr = "";
                         var btnStr2 = "";
                         if (aData.planStatus == "0") {
                              btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;'  ng-click='viewMonthRepay(\"" + aData.id + "\",\"" + aData.planRepaymentDate + "\",\"" + aData.periodNum + "\",\"" + aData.planRepaymentAmount + "\",\"" + $scope.queryParams1.orderNo + "\")'>手动补账</a>";
                         } else if (aData.planStatus == "1") {
                              btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;'  ng-click='viewMonthFinish(\"" + aData.id + "\",\"" + aData.planRepaymentDate + "\",\"" + aData.periodNum + "\",\"" + aData.planRepaymentAmount + "\",\"" + $scope.queryParams1.orderNo + "\")'>查看补账</a>";
                              btnStr2 += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;'  ng-click='viewRepayRecord(\"" + aData.id + "\")'>交易查询</a>";
                         }

                         $(nRow).find(".handle-td").append($compile(btnStr)($scope));
                         $(nRow).find(".viewRecord").append($compile(btnStr2)($scope));

                         if (aData.planStatus == "0") {
                              var statusStr = "未还";
                         } else if (aData.planStatus == "1") {
                              var statusStr = "已还";
                         }

                         $(nRow).find(".repayStatus").empty().append(statusStr);

                         tmpHouseIdArr += aData.houseId + ",";
                         if (iDisplayIndex >= 9) {
                              // console.log(tmpHouseIdArr);
                         }
                    },
                    "fnDrawCallback": function(oSettings) {

                    },
                    "fnServerParams": function(aoData) {

                         aoData.push({
                              'name': 'queryParams',
                              'value': $scope.queryParams
                         });
                         return aoData;
                    },
                    "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
                         //自定义给datatables传递的参数
                         var obj = dataTableObject.oAjaxData,
                              _baseParams = {
                                   // 'page': obj.iDisplayStart / obj.iDisplayLength + 1,
                                   // 'rows': obj.iDisplayLength,
                                   // 'search': 'false',
                                   // 'nd': '1494221804416',
                                   'decorteOrderInfoId': $scope.decorteOrderInfoId
                              };

                         var __data = angular.extend({}, _baseParams, obj.queryParams);
                         rest.decoJava({
                              type: "post",
                              url: sSource,
                              data: __data,
                              beforeSend: function(request) {
                                   request.setRequestHeader("token", token);
                              },
                              success: function(data) {
                                   $scope.myDatas = data;
                                   var data1 = {
                                        'aaData': data.result.decorateRepaymentPlanVoList,
                                        'sEcho': obj.sEcho,
                                        // 'iTotalDisplayRecords': data.pager.recordCount,
                                        // 'iTotalRecords': data.records,
                                   };
                                   fnCallback(data1);
                                   $(dataTableObject.nScrollBody).css('overflow', 'visible');
                                   $(dataTableObject.nScrollBody).css('margin-bottom', 30 + 'px');
                              }
                         });

                         //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
                         //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
                         $scope.search = function() {
                              __data.page = 1;
                              $scope.tableLoanDetailList.fnClearTable();
                         }

                    }
               }
          }

          $scope.initLoanDetailList = function(dataTable) {
               $scope.tableLoanDetailList = dataTable;
          }

          //补账
          $scope.viewMonthRepay = function(id, planRepaymentDate, periodNum, planRepaymentAmount, orderNo) {
               ngDialog.openConfirm({
                    template: 'views/loanOrder/viewMonthRepay.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/controllers/loanOrder/viewMonthRepay.js'])
                                   });
                         }
                    },
                    data: {
                         id: id,
                         planRepaymentDate: planRepaymentDate,
                         periodNum: periodNum,
                         planRepaymentAmount: planRepaymentAmount,
                         orderNo: orderNo
                    },
                    scope: $scope,
                    width: 1000,
                    height: 750
               }).then(function(data) {
                    applyHouseDetail();
                    $scope.tableLoanDetailList.fnClearTable();
               }, function(reason) {
                    applyHouseDetail();
                    $scope.tableLoanDetailList.fnClearTable();
               });
          }

          //查看补账
          $scope.viewMonthFinish = function(id, planRepaymentDate, periodNum, planRepaymentAmount, orderNo) {
               ngDialog.openConfirm({
                    template: 'views/loanOrder/viewMonthFinish.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/controllers/loanOrder/viewMonthFinish.js'])
                                   });
                         }
                    },
                    data: {
                         id: id,
                         planRepaymentDate: planRepaymentDate,
                         periodNum: periodNum,
                         planRepaymentAmount: planRepaymentAmount,
                         orderNo: orderNo
                    },
                    scope: $scope,
                    width: 1000,
                    height: 750
               }).then(function(data) {

               }, function(reason) {

               });
          }

          //交易查询
          $scope.viewRepayRecord = function(id) {
               ngDialog.openConfirm({
                    template: 'views/loanOrder/viewRepayRecord.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/controllers/loanOrder/viewRepayRecord.js'])
                                   });
                         }
                    },
                    data: {
                         id: id
                    },
                    scope: $scope,
                    width: 1000,
                    // height: 750
               }).then(function(data) {

               }, function(reason) {

               });
          }

          //查看月付转换
          $scope.viewMonthChange = function() {
               ngDialog.openConfirm({
                    template: 'views/loanOrder/viewMonthChange.html',
                    resolve: {
                         load: function() {
                              return $ocLazyLoad.load('angularFileUpload').then(
                                   function() {
                                        return uiLoad.load(['js/controllers/loanOrder/viewMonthChange.js'])
                                   });
                         }
                    },
                    data: {
                         id: $scope.queryParams1.id,
                    },
                    scope: $scope,
                    width: 1000,
                    // height: 750
               }).then(function(data) {

               }, function(reason) {

               });
          }

          $scope.$on('loanDate.start', function(event, data) {
               $scope.queryParams1.loanDate = data;
               // console.log(data);
          });

     });

app.controller('ContractTimeCtrl', function($scope) {
     $scope.today = function() {
          $scope.loanStartDate = "";
     };

     $scope.closeAll = function() {
          $scope.openContractBeginDated =
               $scope.openContractEndDated = false;
     }

     $scope.openContractBeginDate = function($event) {
          $event.preventDefault();
          $event.stopPropagation();
          $scope.closeAll();
          $scope.openContractBeginDated = true;
     };

     $scope.dateOptions = {
          format: 'yyyy/MM/dd',
          startingDay: 1,
          class: 'datepicker'
     };

     $scope.format = 'yyyy/MM/dd';

     $scope.today();

     $scope.$watch('loanStartDate', function(newValue, oldValue) {
          if ("[object Date]" === Object.prototype.toString.call(newValue)) {
               $scope.$emit('loanDate.start', moment(newValue).format('YYYY-MM-DD'))
          } else if (null === newValue) {
               $scope.$emit('loanDate.start', '')
          }
     });

});